package com.k.camera2

import android.hardware.Camera
import android.media.CamcorderProfile
import android.media.MediaRecorder
import android.os.Bundle
import android.view.Surface
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.widget.Button
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import java.io.File
import java.io.IOException

class DoubleCameraActivity : AppCompatActivity(), SurfaceHolder.Callback {
    private var camera1: Camera? = null
    private var camera2: Camera? = null
    private var surfaceView1: SurfaceView? = null
    private var surfaceView2: SurfaceView? = null
    private var mediaRecorder1: MediaRecorder? = null
    private var mediaRecorder2: MediaRecorder? = null
    private var isRecording = false
    private var recordButton: Button? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_double_camera)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        initView()
    }

    private fun initView() {
        surfaceView1 = findViewById(R.id.surfaceView1)
        surfaceView2 = findViewById(R.id.surfaceView2)
        recordButton = findViewById(R.id.recordButton)

        surfaceView1?.holder?.addCallback(this)
        surfaceView2?.holder?.addCallback(this)

        recordButton?.setOnClickListener {
            if (isRecording) {
                stopRecording()
                recordButton?.text = "Start Recording"
            } else {
                startRecording()
                recordButton?.text = "Stop Recording"
            }
            isRecording = !isRecording
        }
    }

    override fun surfaceCreated(holder: SurfaceHolder) {
        try {
            camera1 = Camera.open(0) // open first camera
            camera2 = Camera.open(1) // open second camera

            camera1?.setPreviewDisplay(surfaceView1?.holder)
            camera2?.setPreviewDisplay(surfaceView2?.holder)

            camera1?.startPreview()
            camera2?.startPreview()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {}

    override fun surfaceDestroyed(holder: SurfaceHolder) {
        releaseCameraAndPreview()
    }

    private fun startRecording() {
        startRecording(camera1!!, surfaceView1!!.holder.surface, 0)
        startRecording(camera2!!, surfaceView2!!.holder.surface, 1)
    }

    private fun stopRecording() {
        mediaRecorder1?.stop()
        mediaRecorder1?.release()
        mediaRecorder2?.stop()
        mediaRecorder2?.release()
        mediaRecorder1 = null
        mediaRecorder2 = null
    }

    private fun startRecording(camera: Camera, surface: Surface, cameraId: Int) {
        val mediaRecorder = MediaRecorder()
        val profile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH)

        camera.unlock()
        mediaRecorder.setCamera(camera)
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER)
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA)
        mediaRecorder.setProfile(profile)

        val path = PreviewCameraUtils.getSDCardPath() + "/HJ"

//        mediaRecorder.setOutputFile("/sdcard/video_$cameraId.mp4")
//        "${file.path}${File.separator}${fileName}.mp4"
        mediaRecorder.setOutputFile("$path/$cameraId.mp4")
        mediaRecorder.setPreviewDisplay(surface)

        try {
            mediaRecorder.prepare()
            mediaRecorder.start()
        } catch (e: IllegalStateException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        if (cameraId == 0) {
            mediaRecorder1 = mediaRecorder
        } else {
            mediaRecorder2 = mediaRecorder
        }
    }

    private fun releaseCameraAndPreview() {
        mediaRecorder1?.stop()
        mediaRecorder1?.release()
        mediaRecorder2?.stop()
        mediaRecorder2?.release()
        camera1?.release()
        camera2?.release()
        mediaRecorder1 = null
        mediaRecorder2 = null
        camera1 = null
        camera2 = null
    }
}